<template>
	<div class="addProject business-workAdd">
		<div class="addForm zll-form">
			<div style="display: flex;">
				<div class="flex_">
					<span class="_left">罐号：</span>
					<span >{{addForm.deviceCode}}</span>
				</div>
				<div class="flex_">
					<span class="_left">管坯料名：</span>
					<span v-if="!isSelect">{{addForm.gpName}}</span>
					<span v-else>
						<el-select v-model="addForm.gpName" placeholder="" class="text_center" clearable
								   :disabled="addForm.id !=''">
								<el-option :label="m" :value="m" v-for="(m,mindex) in existGyNames" :key="m"></el-option>
							</el-select>
					</span>
				</div>
				<div class="flex_">
					<span class="_left">状态：</span><span>{{addForm.plStatusCn}}</span>
				</div>
				<div v-if="addForm.plStatus == '4'" class="repeat_ban" @click="repeatBan">重新拌料</div>
			</div>
			<div class="tableList" style="margin-top: 10px;">
				<table border="1">
					<tr>
						<th>物料类别</th>
						<th>物料码</th>
						<th>批号</th>
						<th>投料净重 (kg)</th>
						<th>总料重 (kg)</th>
						<th>配比(%)</th>
						<th>配料人</th>
					</tr>
					<tr class="add_Table" v-for="(item,index) in peiAttrs" :key="index">
						<td>{{item.materialType}}</td>
						<td>
							<el-select v-model="item.materialId" placeholder="" class="text_center" clearable
									   :disabled="addForm.id !=''" :popper-append-to-body="!isScreenfull">
								<el-option :label="m.materialName" :value="m.id" v-for="(m,mindex) in getSelectMaterial(materials,item.materialType)" :key="m.id"></el-option>
							</el-select>
						</td>
						<td>
							<el-input @input="item.batchNum=item.batchNum.replace(/[^0-9\.]/g,'')" v-model="item.batchNum" placeholder="" class="text_center" clearable
									  :disabled="addForm.id !=''"></el-input>
						</td>
						<td>
							<el-input  @input="item.jtValue=item.jtValue.replace(/[^0-9\.]/g,'')" v-model="item.jtValue" placeholder="" class="text_center" clearable
									  :disabled="addForm.id !=''" @change="jtValueChange"></el-input>
						</td>
						<template v-if="index == 0">
							<td rowspan="5">{{addForm.totalValue}}</td>
							<td rowspan="5">
								<el-input @input="addForm.ratios=addForm.ratios.replace(/[^0-9\.]/g,'')" v-model="addForm.ratios" placeholder="" class="text_center" clearable
										  :disabled="addForm.id !=''" ></el-input>
							</td>
							<td rowspan="5">{{addForm.plUserName}}</td>
						</template>

					</tr>
				</table>
			</div>
			<div class="nav_list" >
				<div class="_title">
					<span><i class="el-icon-s-promotion"></i>拌料</span>
					<span style="cursor: pointer" @click="takeIn">录入</span>
				</div>
				<div class="tableList" style="margin-top: 0px;">
					<table border="1">
						<tr>
							<th>拌料次数</th>
							<th>开始时间</th>
							<th>结束时间</th>
							<th>拌料时长(min)</th>
							<th>时长指标</th>
							<th>备注</th>
							<th>拌料人</th>
						</tr>
						<tr class="add_Table" v-for="(item,index) in peiBans" :key="index">
							<td>{{'第'+(index+1)+'次拌料' }}</td>
							<td>{{item.startTime}}</td>
							<td>{{item.endTime}}</td>
							<td>{{item.collectTime}}</td>
							<td>
								<span><el-input :disabled="item.peiId != ''"
												@input="item.timeTarget=item.timeTarget.replace(/[^0-9\.]/g,'')"
												v-model="item.timeTarget" placeholder="" class="text_center" clearable></el-input></span>
							</td>
							<td>
								<span><el-input v-model="item.remark" placeholder="" class="text_center" clearable
												:disabled="item.peiId != ''" ></el-input></span>
							</td>
							<td>{{item.banUserName}}</td>
						</tr>
					</table>
				</div>
			</div>
			<div class="nav_list" v-show="addForm.plStatus >1">
				<div class="_title">
                    <span>
                        <i class="el-icon-s-promotion" >出料</i>
                        <span style="color: #9e9e9e;">（ 未出料：<i style="color: #f44336">{{noOutValue}}</i> kg ）</span>
                    </span>
					<span style="cursor: pointer;" @click="outPei" v-if="addForm.plStatus =='3'">立即出料</span>
				</div>
				<div class="tableList" style="margin-top: 0px;">
					<table border="1">
						<tr>
							<th>车次</th>
							<th>出料重量（kg）</th>
							<th>挤塑机号</th>
							<th>出料人/时间</th>
						</tr>
						<tr class="add_Table" v-for="(item,index) in peiOuts" :key="index">
							<td>{{index+1}}</td>
							<td>{{item.clValue}}</td>
							<td>{{item.machineName}}</td>
							<td>{{item.clUserName+'/'+item.createTimeFt}}</td>
						</tr>
					</table>
				</div>
			</div>
		</div>
		<div class="zll-dialog">
			<popout title="出料" :visible.sync="addDialog" v-if="addDialog" class="long_size">
				<chu ref="add" slot="content" :items="itemList" :editData="chuData"></chu>
				<template slot="bottom">
					<p class="zll-botton Info" @click="addDialog = false">关 闭</p>
					<p class="zll-botton"  @click="()=>{this.$refs.add.chuPei('addForm')}">出料</p>
				</template>
			</popout>
		</div>
	</div>
</template>
<script>
	import {getStore} from "@/plugins/localStore";
	import {formatDate} from "@/plugins/formatDate";
	import chu from './chu'
	export default {
		props: ['editData', 'type','isScreenfull'],
		data() {
			return {
				addForm: {
					id:'',
					deviceCode:'',
					gpName:'',
					zlValue:'',
					flValue:'',
					smValue:'',
					ratios:'',
					totalValue:'',
					plUserName:'',
					plUserId:'',
					plStatus:'',
					plStatusCn:'',
					dutyDay:'',
				},
				rules: {

				},
				count: 0,
				user: {},
				materials:[],
				peiAttrs:[],
				peiBans:[],
				peiOuts:[],

				isSelect:false,
				existGyNames:['U直','伸直','普直'],

				noOutValue:0,

				showOut:false,
				takeInFlag:false,

				addDialog:false,
				chuData:{noOutValue:'',deviceCode:'',gpName:'',clValue:'',machineName:'',clUserName:'',peiId:''},
				itemList:[],
			}
		},
		methods: {

			repeatBan(){
				this.$emit('setRepeatFlag')
				this.addForm.plStatus = '0';
				this.addForm.oldId = this.addForm.id;
				this.addForm.id = '';
				this.peiBans = [];
			},

			outPei(){
				let self = this;
				self.addDialog = true;
				self.$nextTick(() => {
					self.chuData = {noOutValue:self.noOutValue,deviceCode:self.addForm.deviceCode,gpName:self.addForm.gpName,clValue:'',machineName:'',clUserName:self.user.userName,peiId:self.addForm.id};
					let itemList = self.itemList.filter((item)=>item.itemName == self.addForm.gpName);
					self.itemList = JSON.parse(JSON.stringify(itemList));
				});
			},

			takeIn(){
				if(this.addForm.plStatus !='0'&&this.addForm.plStatus !='2'){
					this.$message.warning('无法录入拌料！');
					return;
				}
				if(!this.takeInFlag){
					// let time = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
					this.takeInFlag = true;
					this.peiBans.push({banName:this.addForm.deviceCode,peiId:'',startTime:'',endTime:'',collectTime:'',timeTarget:'',remark:'',banUserName:this.user.userName})
				}else{
					this.$message.warning('只能录入一次拌料！');
				}
			},

			jtValueChange(){
				let totalValue = 0.0;
				for(let data of this.peiAttrs){
					let jtValue = data.jtValue;
					if(jtValue){
						totalValue+=parseFloat(jtValue);
					}
				}
				this.addForm.totalValue = totalValue.toFixed(2)+'';
			},

			doubleBanLiao(){
				for(let data of this.peiBans){
					if(!data.timeTarget){
						this.$message.warning('请录入拌料指标信息！');
						return;
					}
				}
				if(this.count == 0){
					let self = this;
					let params = Object.assign({},self.addForm)
					params.linePeiBans = self.peiBans.filter((item)=>item.flag!='1');
					self.$http({
						url: "/jinl/linepei/updateLinePei",
						method: "post",
						data: JSON.stringify(params),
						dataType: 'json',
						contentType: "application/json",
					}).then(resp => {
						if (resp.success) {
							console.log(resp.result);
							self.$message.success('保存二次拌料成功')
							self.$eventBus.$emit('updateLinePeiList');
							return;
						}
						self.$message.error(resp.message)
						self.count = 0;
					});
				}
			},

			banLiao(){
				if(this.peiAttrs.length == 0){
					this.$message.warning('配料异常！');
					return;
				}
				let peiAttrs = this.peiAttrs.filter((item)=> item.materialType&&item.materialId&&item.batchNum&&item.jtValue)
				// for(let data of this.peiAttrs){
				// 	if(!data.materialType||!data.materialId||!data.batchNum||!data.jtValue){
				// 		this.$message.warning('请填写完成配料信息！');
				// 		return;
				// 	}
				// }
				if(peiAttrs.length == 0){
					this.$message.warning('请填写完成配料信息！');
					return;
				}
				if(!this.addForm.ratios){
					this.$message.warning('请填写配比！');
					return;
				}
				if(this.peiBans.length == 0){
					this.$message.warning('请录入拌料信息！');
					return;
				}
				for(let data of this.peiBans){
					if(!data.timeTarget){
						this.$message.warning('请录入拌料指标信息！');
						return;
					}
				}
				if(this.count == 0){
					let self = this;
					let params = Object.assign({},self.addForm)
					params.linePeiBans = self.peiBans;
					params.linePeiAttrs = peiAttrs;
					self.$http({
						url: "/jinl/linepei/updateLinePei",
						method: "post",
						data: JSON.stringify(params),
						dataType: 'json',
						contentType: "application/json",
					}).then(resp => {
						if (resp.success) {
							console.log(resp.result);
							self.$message.success('拌料成功')
							self.$eventBus.$emit('updateLinePeiList');
							return;
						}
						self.$message.error(resp.message)
						self.count = 0;
					});
				}
			},

			submitForm(val, type) {
				let self = this;

			},

			getSingleMaterialSelect() {
				let self = this;
				self.materials = [];
				self.$http({
					url: "/jinl/material/getMaterialWithItemName",
					method: "post",
				}).then(resp => {
					if (resp.success) {
						console.log(resp.result)
						self.materials = resp.result;
					}
				});
			},

			getSelectMaterial(materials,mtype){
				console.log(mtype)
				let selects = (materials||[]).filter((item) =>item.itemAlias == mtype);
				return selects||[];
			},

			getLinePeiAttrs(peiId) {
				let self = this;
				self.peiAttrs = [];
				self.$http({
					url: "/jinl/linepei/getLinePeiAttrs",
					method: "post",
					params:{peiId:peiId}
				}).then(resp => {
					if (resp.success) {
						console.log(resp.result)
						self.peiAttrs = resp.result;
					}
				});
			},

			getLinePeiBans(peiId) {
				let self = this;
				self.peiBans = [];
				self.$http({
					url: "/jinl/linepei/getLinePeiBans",
					method: "post",
					params:{peiId:peiId}
				}).then(resp => {
					if (resp.success) {
						console.log('-------getLinePeiBans-----------')
						console.log(resp.result)
						for(let data of resp.result){
							data.flag = '1';
						}
						self.peiBans = resp.result;
					}
				});
			},

			getLinePeiOuts(peiId) {
				let self = this;
				self.peiOuts = [];
				self.$http({
					url: "/jinl/linepei/getLinePeiOuts",
					method: "post",
					params:{peiId:peiId}
				}).then(resp => {
					if (resp.success) {
						console.log(resp.result)
						self.peiOuts = resp.result;
						let hasOut = 0.0;
						for(let data of self.peiOuts){
							hasOut += parseFloat(data.clValue);
						}
						let noOut = parseFloat(self.addForm.totalValue) - hasOut;
						self.noOutValue = noOut.toFixed(2)+'';
					}
				});
			},

			getSysItemList() {
				let self = this;
				self.itemList = [];
				self.$http({
					url: "/jinl/sysItem/getMgItemSelect",
					method: "post",
					data: JSON.stringify({types: ['4']}),
					dataType: 'json',
					contentType: "application/json",
				}).then(resp => {
					if (resp.success) {
						self.itemList = resp.result;
					}
				});
			},

		},

		watch: {
			editData(val) {
				console.log(val)
				this.user = getStore();
				this.count = 0;
				for (let key in  this.addForm) {
					this.addForm[key] = val[key] || ''
				}
				if(!this.addForm.id){
					this.addForm.plUserName = this.user.userName;
					this.addForm.plUserId = this.user.id;
				}
				if(this.addForm.plStatus=='0' && (this.addForm.deviceCode !='B01' && this.addForm.deviceCode !='B02' &&this.addForm.deviceCode !='B03')){
					this.isSelect = true;
				}
				this.getSingleMaterialSelect();
				this.getLinePeiAttrs(this.addForm.id);
				this.getLinePeiBans(this.addForm.id);
				this.getLinePeiOuts(this.addForm.id);
			},

		},

		mounted() {
			let self = this;
			this.getSysItemList();
			self.$eventBus.$on("updateOutPei", function (val) {
				self.addDialog = false;
				self.getLinePeiOuts(self.addForm.id);
			})
		},
		components:{
			chu
		}
	}
</script>
<style lang="scss" scoped>
	@import "@/style/dialog.scss";

	.flex_ {
		width: 150px;
		display: flex;align-items: center;

		._left {
			color: #9e9e9e;
		}
		.text_center {
			width: 80px;
		}
	}

	.repeat_ban{
		position: absolute;
		right: 80px;
		color: #409eff;
		cursor: pointer;
	}

	.nav_list {
		margin-top: 20px;

		._title {
			line-height: 40px;
			color: #00D1D0;
			display: flex;
			justify-content: space-between;

			i {
				font-size: 16px;
				margin-right: 5px;
			}
		}

		.edit_ {
			color: #409EFF;
			cursor: pointer;
		}
	}
</style>